package com.lanhu.datastructure.stack;

import java.util.EmptyStackException;

/**
 * @author 蓝狐
 */
public class LinkedStack<T> implements Stack{
    /**
     * 栈顶
     */
    private StackNode head;

    /**
     * 栈大小
     */
    private int size;


    @Override
    public boolean isEmpty () {
        return size == 0;
    }

    /**
     * 出栈
     * @return
     */
    @Override
    public Object pop () {
        if (size == 0) {
            throw new EmptyStackException();
        }
        Object data = head.getData();
        head = head.getNext();
        size --;
        return data;
    }

    /**
     * 入栈
     * @param o
     * @return
     */
    @Override
    public Object push (Object o) {
        StackNode stackNode = new StackNode(o, null);
        if (size == 0){
            head = stackNode;
            size ++;
        } else {
            stackNode.setNext(head);
            head = stackNode;
            size ++;
        }
        return o;
    }

    @Override
    public void clear () {
        if (size == 0){
            return;
        }
        head = null;
        size = 0;
    }

    /**
     * 返回栈顶数据，但不出栈
     * @return
     */
    @Override
    public Object peek () {
        if (size == 0){
            throw new EmptyStackException();
        }
        return head.getData();
    }

    /**
     * 返回链的长度
     * @return
     */
    @Override
    public int length () {
        return size;
    }

    @Override
    public int search (Object o) {
        if (size == 0){
            throw new EmptyStackException();
        }
        int count = 0;
        int tmp = 0;

        StackNode stackNode = head;
        while (stackNode !=null){

            count ++;
            if (stackNode.getData().equals(o)){
                tmp = 1;
                break;
            }

            stackNode = stackNode.getNext();
        }
        if (tmp == 1){
            return count;
        }
        return -1;
    }
}
